package com.airnewslinkosky.ticket.ui.flight;

import java.util.Calendar;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.airnewslinkosky.ticket.R;
import com.airnewslinkosky.ticket.model.Flight;
import com.airnewslinkosky.ticket.model.SearchFlight;
import com.airnewslinkosky.ticket.net.WebAccessor;
import com.airnewslinkosky.ticket.sql.FavoriteInfoDB;
import com.airnewslinkosky.ticket.ui.BaseActivity;
import com.airnewslinkosky.ticket.ui.CityList;
import com.airnewslinkosky.ticket.ui.Main;
import com.airnewslinkosky.ticket.util.AddrUtil;
import com.airnewslinkosky.ticket.util.Constants;
import com.airnewslinkosky.ticket.util.DateUtil;
import com.airnewslinkosky.ticket.util.FlyUtil;
import com.mobclick.android.MobclickAgent;

/**
 * 航班查询
 * @author zouxs
 */
public class FlightRoundQuery extends BaseActivity {
	
	public final int CITY_LIST = 1;
	public final int FLYCOM_LIST = 2;
	public final int NORESULT = 3;
	public final int NOORDER = 4;
	public final int NOORDERSTAT = 5;
	public final int NET_ERROR=6;
	public final int SEARCH_ERROR=7;
	public  final int TIME_DIALOG_ID = 8;
	public  final int DIALOG_SINGLE_CHOICE = 9;
	public  final int DIALOG_LIST = 10;
	public  final int FROM_DATE_DIALOG_ID = 11;
	public  final int TO_DATE_DIALOG_ID = 12;
	
	public  final int RETURN_STATS = -2000;
	
	public static SearchFlight searchFlight;
	
	private TextView comCity,toCity,fromDate,toDate,airCompany,classGrade;
	//出发城市,到达城市,出发日期,回程日期，航空公司,舱位等级
	private LinearLayout fromCityLay,toCityLay,fromDateLay,toDateLay,airCompanyLay,classGradeLay;
	//查询，单程，双程
	private Button flySearchBut,singleBut,roundBut;
	
	private ImageView backBut;
	
	private ProgressDialog progressDialog = null;
	public Handler myHandler;
	
	AddrUtil addrUtil;
	
	private int postion=0;
	private int mYear;
    private int mMonth;
    private int mDay;
    private String fromDateStr,toDateStr;
    
    private SharedPreferences sp;
	private String loginNameRe = "";
	private String isLoninOK = null;//是否登录
	private String autoLogin = null;//记着登录
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.flight_rount_query);
		// 删除窗口背景
        getWindow().setBackgroundDrawable(null);
		activityList.add(this);
		addrUtil = new AddrUtil(this);
		
		sp = getSharedPreferences("UserInfoB2B", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
		initConfig();
		
		fromCityLay = (LinearLayout)findViewById(R.id.fromCityLay);
		toCityLay = (LinearLayout)findViewById(R.id.toCityLay);
		fromDateLay = (LinearLayout)findViewById(R.id.fromDateLay);
		toDateLay = (LinearLayout)findViewById(R.id.toDateLay);
		airCompanyLay = (LinearLayout)findViewById(R.id.airCompanyLay);
		classGradeLay = (LinearLayout)findViewById(R.id.classGradeLay);
		
		comCity = (TextView)findViewById(R.id.comCity);
		toCity = (TextView)findViewById(R.id.toCity);
		
		comCity.setText(FavoriteInfoDB.selectFlySetInfoValue(this, Constants.SYSTEM_TYPE_COM_CITY));
		toCity.setText(FavoriteInfoDB.selectFlySetInfoValue(this, Constants.SYSTEM_TYPE_TO_CITY));
		
		
		
		//得到当前日期
        final Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
        fromDateStr = mYear+"-"+DateUtil.pad(mMonth+1)+"-"+DateUtil.pad(mDay+1);
        fromDate = (TextView)findViewById(R.id.fromDate);
        fromDate.setText(fromDateStr + " " + DateUtil.getWeek("yyyy-MM-dd", fromDateStr));
        
        calendar.add(Calendar.DATE, 1);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
        toDateStr = mYear+"-"+DateUtil.pad(mMonth+1)+"-"+DateUtil.pad(mDay+1);
        toDate = (TextView)findViewById(R.id.toDate);
        toDate.setText(toDateStr + " " + DateUtil.getWeek("yyyy-MM-dd", toDateStr));
        
		airCompany = (TextView)findViewById(R.id.airCompany);
		classGrade = (TextView)findViewById(R.id.classGrade);
		
		flySearchBut = (Button)findViewById(R.id.flySearchBut);
		singleBut = (Button)findViewById(R.id.singleBut);
		roundBut = (Button)findViewById(R.id.roundBut);
		
		backBut = (ImageView) findViewById(R.id.backBut);
		
		OnClickListener b_ocl= new OnClickListener() { 
	    	public void onClick(View v) { 
	    		switch (v.getId()) {
	    		case R.id.fromCityLay:
	    			Intent intent = new Intent();
	    			intent.setClass(FlightRoundQuery.this, CityList.class);
	    			intent.putExtra("comcity", toCity.getText().toString());
	    			startActivityForResult(intent, R.id.comCity);
	    			break;
	    		case R.id.toCityLay:
	    			Intent intentTo = new Intent();
	    			intentTo.setClass(FlightRoundQuery.this, CityList.class);
	    			intentTo.putExtra("comcity", comCity.getText().toString());
	    			startActivityForResult(intentTo, R.id.toCity);
	    			break;
	    		case R.id.airCompanyLay:
	    			showDialog(DIALOG_SINGLE_CHOICE);
	    			break;
	    		case R.id.classGradeLay:
	    			showDialog(DIALOG_LIST);
	    			break;
	    		case R.id.fromDateLay:
	    			showDialog(FROM_DATE_DIALOG_ID);
	    			break;
	    		case R.id.toDateLay:
	    			showDialog(TO_DATE_DIALOG_ID);
	    			break;
	    		case R.id.flySearchBut:
	    			search();
	    			break;
	    		case R.id.singleBut:
	    			Intent intentS = new Intent();
	    			intentS.setClass(FlightRoundQuery.this, FlightQuery.class);
	    			SearchFlight searchFlight = new SearchFlight();
					searchFlight.departure = addrUtil.getCodeByCity(comCity.getText().toString());
					searchFlight.arrival = addrUtil.getCodeByCity(toCity.getText().toString());
					searchFlight.fcity = comCity.getText().toString();
					searchFlight.tcity = toCity.getText().toString();
					searchFlight.departureDate = fromDateStr + " " + DateUtil.getWeek("yyyy-MM-dd", fromDateStr);
					searchFlight.returnDate = toDateStr + " " + DateUtil.getWeek("yyyy-MM-dd", toDateStr);
					searchFlight.ftype = "single";
					searchFlight.airline = airCompany.getText().toString().equals("不限") ? "" : FlyUtil.getAirlineKey(airCompany.getText().toString());
					searchFlight.fclassGrade = classGrade.getText().toString();
					FlightQuery.searchFlight = searchFlight;
					intentS.putExtra("searchFlight", searchFlight);
	    			setResult(RETURN_STATS, intentS);
	    			finish();
	    			break;
	    		case R.id.roundBut:
	    			break;
	    		case R.id.backBut:
	    			Intent intentR = new Intent();
	    			intentR.setClass(FlightRoundQuery.this, Main.class);
	    			Bundle bundle=new  Bundle();
	    			bundle.putString("loginNameB2B", loginNameRe);
	    			bundle.putString("isLoninOKB2B", isLoninOK);
	    			bundle.putString("autoLoginB2B", autoLogin);
//	    			sp.edit().putString("loginNameB2B",loginNameRe).commit();
//	    			sp.edit().putString("isLoninOKB2B",isLoninOK).commit();
//	    			sp.edit().putString("isAutoLoginB2B",autoLogin).commit();
	    			intentR.putExtras(bundle);
	    			setResult(RESULT_OK, intentR);
	    			finish();
					break;
	    		}
	    	}
		};
		
		backBut.setOnClickListener(b_ocl);
		
		fromCityLay.setOnClickListener(b_ocl);
		toCityLay.setOnClickListener(b_ocl);
		airCompanyLay.setOnClickListener(b_ocl);
		classGradeLay.setOnClickListener(b_ocl);
		fromDateLay.setOnClickListener(b_ocl);
		toDateLay.setOnClickListener(b_ocl);
		
		flySearchBut.setOnClickListener(b_ocl);
		singleBut.setOnClickListener(b_ocl);
		roundBut.setOnClickListener(b_ocl);
		
		myHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case NORESULT:
					Toast.makeText(FlightRoundQuery.this, "未找到符合条件的航班", Toast.LENGTH_LONG)
							.show();
					break;
				case NOORDER:
					Toast.makeText(FlightRoundQuery.this, "无订单信息", Toast.LENGTH_LONG)
							.show();
					break;
				case NOORDERSTAT:
					Toast.makeText(FlightRoundQuery.this, "订单信息未获得更新", Toast.LENGTH_LONG)
							.show();
					break;
				case NET_ERROR:
					Toast.makeText(FlightRoundQuery.this, "网络超时，连接失败", Toast.LENGTH_LONG)
					.show();
					break;
				case SEARCH_ERROR:
					Toast.makeText(FlightRoundQuery.this, (String)msg.obj, Toast.LENGTH_LONG)
					.show();
					break;
				}
				super.handleMessage(msg);
			}
		};
		
	}

    //初始化配置
    private void initConfig() {
//    	sp = getSharedPreferences("UserInfoB2B", 0);
//        loginNameRe = sp.getString("loginNameB2B", "");
//        isLoninOK = sp.getString("isLoninOKB2B", null);
//        autoLogin = sp.getString("isAutoLoginB2B", null);
        
        SearchFlight searchFlight = (SearchFlight)getIntent().getExtras().get("searchFlight");  
        System.out.println("round searchFlight  === " +searchFlight);
	    if(searchFlight!=null){
			comCity.setText(searchFlight.fcity);
			toCity.setText(searchFlight.tcity);
			fromDate.setText(searchFlight.departureDate + " " + DateUtil.getWeek("yyyy-MM-dd", fromDateStr));
			fromDateStr = searchFlight.departureDate;
			airCompany.setText(searchFlight.airline);
			classGrade.setText(searchFlight.fclassGrade);
			toDate.setText(searchFlight.returnDate + " " + DateUtil.getWeek("yyyy-MM-dd", searchFlight.returnDate));
			toDateStr = searchFlight.returnDate;
	    }
    }
    
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		    case DIALOG_LIST:
	            return new AlertDialog.Builder(FlightRoundQuery.this)
	                .setIcon(R.drawable.alert_dialog_icon)
	                .setTitle("请选择")
	                .setSingleChoiceItems(R.array.flight_class_type, 0, new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	postion = whichButton;
	                    	String[] arrs = getResources().getStringArray(R.array.flight_class_type);
	                    	classGrade.setText(arrs[whichButton]);
	                    	dialog.dismiss();
	                        /* User clicked on a radio button do some stuff */
	                    }
	                })
	                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    
	                    }
	                })
	                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    }
	                })
	               .create();
		    case DIALOG_SINGLE_CHOICE:
	            return new AlertDialog.Builder(FlightRoundQuery.this)
	                .setIcon(R.drawable.alert_dialog_icon)
	                .setTitle("请选择")
	                .setSingleChoiceItems(R.array.airlineList, 0, new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	postion = whichButton;
	                    	String[] arrs = getResources().getStringArray(R.array.airlineList);
	                    	airCompany.setText(arrs[whichButton]);
	                    	dialog.dismiss();
	                        /* User clicked on a radio button do some stuff */
	                    }
	                })
	                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    
	                    }
	                })
	                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    }
	                })
	               .create();
		    case FROM_DATE_DIALOG_ID:
		    	return new DatePickerDialog(this, fdsl, mYear, mMonth, mDay);
		    case TO_DATE_DIALOG_ID:
		    	return new DatePickerDialog(this, tdsl, mYear, mMonth, mDay);
		default:
			return null;
		}
	}

    //准备日期设置监听器
    private OnDateSetListener fdsl = new DatePickerDialog.OnDateSetListener(){

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear =year;
			mMonth= monthOfYear;
			mDay= dayOfMonth;
			fromDateStr = mYear+"-"+DateUtil.pad(mMonth+1)+"-"+DateUtil.pad(mDay);
	        fromDate.setText(fromDateStr + " " + DateUtil.getWeek("yyyy-MM-dd", fromDateStr));
		}
    };
 
    //准备日期设置监听器
    private OnDateSetListener tdsl = new DatePickerDialog.OnDateSetListener(){

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear =year;
			mMonth= monthOfYear;
			mDay= dayOfMonth;
	        toDateStr = mYear+"-"+DateUtil.pad(mMonth+1)+"-"+DateUtil.pad(mDay);
	        toDate.setText(toDateStr + " " + DateUtil.getWeek("yyyy-MM-dd", toDateStr));
		}
    };
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			TextView tv = (TextView) findViewById(requestCode);
			Bundle b=data.getExtras();  
			tv.setText(b.getString("city"));
			tv.requestFocus();
		} else if(resultCode == RETURN_STATS) {
			initConfig();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void search() {
		final String fcity = comCity.getText().toString();
		final String tcity = toCity.getText().toString();
		final String fdate = fromDateStr;
		final String tdate = toDateStr;
		final String fairCompany = airCompany.getText().toString();
		final String fclassGrade = classGrade.getText().toString();
		
		if (fcity.equals("") || tcity.equals("") || fdate.equals("")) {
			Toast.makeText(this, "请选择完整信息", Toast.LENGTH_LONG).show();
			return;
		}
		
		if (fcity.equals(tcity)) {
			Toast.makeText(this, "出发城市与到达城市不能相同\n              请重新选择", Toast.LENGTH_LONG).show();
			return;
		}
		
		progressDialog = ProgressDialog.show(this, "请稍等...", "查询机票中...",
				true);
		final Thread thread1 = new Thread() {
			public void run() {
				SearchFlight searchFlight = new SearchFlight();
				searchFlight.departure = addrUtil.getCodeByCity(fcity);
				searchFlight.arrival = addrUtil.getCodeByCity(tcity);
				searchFlight.fcity = fcity;
				searchFlight.tcity = tcity;
				searchFlight.ftype = "round";
				searchFlight.departureDate = fdate;
				searchFlight.airline = fairCompany.equals("不限") ? "" : FlyUtil.getAirlineKey(fairCompany);
				searchFlight.fclassGrade = fclassGrade.equals("不限") ? "" : FlyUtil.getJClassCode(fclassGrade);;
				
				Flight flight =  WebAccessor.GetFlightTicket(FlightRoundQuery.this,searchFlight);
				if (progressDialog.isShowing()) {
					if (flight== null) {
						Message msg = new Message();
						msg.what = NORESULT;
						myHandler.sendMessage(msg);
					}else if(!"0".equals(flight.resultcode)){
						Message msg = new Message();
						msg.what = SEARCH_ERROR;
						msg.obj = flight.message;
						myHandler.sendMessage(msg);
					}else{
						Intent intent3 = new Intent();
						intent3.setClass(FlightRoundQuery.this, FlyList.class);
						intent3.putExtra("tdate", tdate);
						FlyList.searchFlight = searchFlight;
						FlyList.flist = flight.flightInfos;
						startActivity(intent3);
					}
					progressDialog.dismiss();
				}
			}
		};
		progressDialog.setCancelable(true);
		thread1.start();
	}
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  

}